package com.yingpai.fitness.dvp_2_0.main.activity.vip;

import android.app.AlertDialog;
import android.app.Dialog;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.yingpai.fitness.R;
import com.yingpai.fitness.base.BaseResponse;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.adapter.BaseAdapterHelper;
import com.yingpai.fitness.dvp_2_0.common.adapter.QuickAdapter;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.main.activity.ProtocolActivity;
import com.yingpai.fitness.dvp_2_0.main.bean.vip.VipRenewBean;
import com.yingpai.fitness.dvp_2_0.main.bean.pay.ChongZhiDingDanEntiy;
import com.yingpai.fitness.dvp_2_0.main.bean.pay.ZfbChongZhiEntity;
import com.yingpai.fitness.dvp_2_0.main.callback.WechatCallBack;
import com.yingpai.fitness.dvp_2_0.main.util.PayUtil;
import com.yingpai.fitness.dvp_2_0.main.util.WechatLoginUtil;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ASUS on 2019/1/11.
 */

public class VipRenewActivity extends CommonActivity implements PayUtil.codeResultClickInterface, WechatCallBack {
    @BindView(R.id.gridview)
    GridView gridview;
    @BindView(R.id.weChatPayCb)
    CheckBox weChatPayCb;
    @BindView(R.id.aLiPayCb)
    CheckBox aLiPayCb;
    @BindView(R.id.vip_money)
    TextView vipMoney;
    @BindView(R.id.vip_name)
    TextView vipName;
    private String tag = "";
    private QuickAdapter<VipRenewBean.DataBean> quickAdapter;
    private String vipCardId = "";
    private String orderId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusFlag(Contacts.NORMAL_STATUS);
        setContentView(R.layout.activity_vip_renew);
    }

    @Override
    protected void initView() {
        setTitle("VIP会员续费");

        tag = Constant.WECHAT;
        weChatPayCb.setChecked(true);

        quickAdapter = new QuickAdapter<VipRenewBean.DataBean>(this, R.layout.item_vip_renew) {
            @Override
            protected void convert(BaseAdapterHelper helper, VipRenewBean.DataBean item) {
                LinearLayout itemLl = helper.getView(R.id.item_ll);
                if (item.isSelect()) {
                    itemLl.setBackground(getResources().getDrawable(R.drawable.shape_item_vip_renew));
                } else {
                    itemLl.setBackground(getResources().getDrawable(R.drawable.shape_item_vip_renew_normal));
                }
                helper.setText(R.id.name, item.getName());
                helper.setText(R.id.price, "￥" + item.getPrice());

                TextView common_price = helper.getView(R.id.common_price);
                common_price.setText("￥" + item.getOldPrice());
                common_price.setPaintFlags(common_price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            }
        };

        gridview.setAdapter(quickAdapter);

        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                for (int i = 0; i < quickAdapter.getCount(); i++) {
                    quickAdapter.getItem(i).setSelect(false);
                }
                quickAdapter.getItem(position).setSelect(true);
                vipCardId = quickAdapter.getItem(position).getId();
                vipMoney.setText("￥" + quickAdapter.getItem(position).getPrice());
                vipName.setText("您已选择" + quickAdapter.getItem(position).getName());
                quickAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected void initData() {
        requestData();
    }

    private void requestData() {
        showDialog(this, null);
        finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.VIP_RENEW, null, Url.VIP_RENEW, new Callback<VipRenewBean>() {
            @Override
            public void onSuccess(VipRenewBean vipRenewBean) {
                if (vipRenewBean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                    vipCardId = vipRenewBean.getData().get(0).getId();
                    vipMoney.setText("￥" + vipRenewBean.getData().get(0).getPrice());
                    vipName.setText("您已选择VIP" + vipRenewBean.getData().get(0).getName());
                    vipRenewBean.getData().get(0).setSelect(true);
                    quickAdapter.clear();
                    quickAdapter.addAll(vipRenewBean.getData());
                    quickAdapter.notifyDataSetChanged();
                } else {
                    showToast(vipRenewBean.getMessage() + "");
                }
                dismissDialog();
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });
    }

    @Override
    @OnClick({R.id.weChatPayCb, R.id.aLiPayCb, R.id.buy, R.id.vip_question})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.vip_question:
                Bundle bundle = new Bundle();
                bundle.putString("title", "会员须知");
                startActivity(ProtocolActivity.class, bundle);
                break;
            case R.id.weChatPayCb:
                if (weChatPayCb.isChecked()) {
                    tag = Constant.WECHAT;
                    aLiPayCb.setChecked(false);
                } else {
                    tag = "";
                }
                break;
            case R.id.aLiPayCb:
                if (aLiPayCb.isChecked()) {
                    tag = Constant.ALIPAY;
                    weChatPayCb.setChecked(false);
                } else {
                    tag = "";
                }
                break;
            case R.id.buy:
                if (!vipCardId.equals("")) {
                    if (tag.equals(Constant.ALIPAY)) {
                        showDialog(this, "支付中...");
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("vipCardId", vipCardId);
                        finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.VIP_RENEW_ALIPAY, map, Url.VIP_RENEW_ALIPAY, new Callback<ZfbChongZhiEntity>() {
                            @Override
                            public void onSuccess(ZfbChongZhiEntity zfbChongZhiEntity) {
                                if (zfbChongZhiEntity.getResult().equals(Constant.REQUEST_SUCCESS)) {
                                    orderId = zfbChongZhiEntity.getMap().getId();
                                    PayUtil.zfbpay(VipRenewActivity.this, VipRenewActivity.this, zfbChongZhiEntity.getMap().getResponse());
                                } else {
                                    showToast(zfbChongZhiEntity.getMsg() + "");
                                }
                            }

                            @Override
                            public void onError(Response<String> response) {
                                super.onError(response);
                                dismissDialog();
                            }
                        });
                    } else if (tag.equals(Constant.WECHAT)) {
                        showDialog(this, "支付中...");
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("vipCardId", vipCardId);
                        finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.VIP_RENEW_WECHAT, map, Url.VIP_RENEW_WECHAT, new Callback<ChongZhiDingDanEntiy>() {
                            @Override
                            public void onSuccess(ChongZhiDingDanEntiy chongZhiDingDanEntiy) {
                                if (chongZhiDingDanEntiy.getResult().equals(Constant.REQUEST_SUCCESS)) {
                                    orderId = chongZhiDingDanEntiy.getMap().getId();
                                    WechatLoginUtil.getInstance().setWechatCallBack(VipRenewActivity.this);
                                    PayUtil.wxpay(getApplicationContext(), chongZhiDingDanEntiy.getMap().getResponse().getAppid(),
                                            chongZhiDingDanEntiy.getMap().getResponse().getPartnerid(),
                                            chongZhiDingDanEntiy.getMap().getResponse().getPrepayid(),
                                            chongZhiDingDanEntiy.getMap().getResponse().getNoncestr(),
                                            chongZhiDingDanEntiy.getMap().getResponse().getTimestamp() + "",
                                            chongZhiDingDanEntiy.getMap().getResponse().getSign());
                                } else {
                                    showToast(chongZhiDingDanEntiy.getMsg());
                                }
                            }

                            @Override
                            public void onError(Response<String> response) {
                                super.onError(response);
                                dismissDialog();
                            }
                        });
                    } else {
                        showToast("请选择支付方式");
                    }
                } else {
                    showToast("请选择会员卡");
                }
                break;
        }
    }

    @Override
    public void ZFBSuccess(String code) {
        dismissDialog();
        HashMap<String, Object> map = new HashMap<>();
        map.put("orderId", orderId);
        map.put("payMode", Constant.NUM_1 + "");
        finalOkGo.requestEncrypt(RequestType.POSTENCRYPT,
                Contacts.HOST_SERVER + Url.RENEW_PAY_NOTIFY, map, Url.RENEW_PAY_NOTIFY, new Callback<BaseResponse>() {
            @Override
            public void onSuccess(BaseResponse baseResponse) {
                if (baseResponse.getResult().equals(Constant.REQUEST_SUCCESS)) {
                    showSuccessDialog();
                } else {
                    showFaileDialog();
                }
            }

            @Override
            public void onError(Response response) {
                super.onError(response);
                showFaileDialog();

            }
        });
    }

    @Override
    public void ZFBFail(String code) {
        showFaileDialog();
    }

    @Override
    public void ZFBResultQueRen(String code) {

    }

    @Override
    public void callBack(BaseResp baseResp) {
        dismissDialog();
        if(baseResp.errCode != BaseResp.ErrCode.ERR_OK){
            return;
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("orderId", orderId);
        map.put("payMode", Constant.NUM_2 + "");
        finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.RENEW_PAY_NOTIFY, map, Url.RENEW_PAY_NOTIFY, new Callback<BaseResponse>() {
            @Override
            public void onSuccess(BaseResponse baseResponse) {
                if (baseResponse.getResult().equals(Constant.REQUEST_SUCCESS)) {
                    showSuccessDialog();
                } else {
                    showFaileDialog();
                }
            }

            @Override
            public void onError(Response response) {
                super.onError(response);
                showFaileDialog();

            }
        });
    }

    private void showSuccessDialog() {
        LayoutInflater mInflater = LayoutInflater.from(this);
        LinearLayout dialog_pay_success = (LinearLayout) mInflater.inflate(R.layout.dialog_shop_pay_success, null);
        Dialog dialog = new AlertDialog.Builder(this, R.style.NoBackGroundDialog).create();

        dialog_pay_success.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(Constant.REQUEST_SUCCESS);
                finish();
            }
        });

        dialog.show();
        dialog.setContentView(dialog_pay_success);
    }

    private void showFaileDialog() {
        LayoutInflater mInflater = LayoutInflater.from(this);
        LinearLayout dialog_pay_faile = (LinearLayout) mInflater.inflate(R.layout.dialog_pay_faile, null);
        Dialog dialog = new AlertDialog.Builder(this, R.style.NoBackGroundDialog).create();
        dialog.show();
        dialog.setContentView(dialog_pay_faile);
    }
}
